package com.simple.orm.agreement.utils;

import com.alibaba.fastjson.JSON;

import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class DataOutputStreamUtil {

    public static void writeData(DataOutputStream dataOutputStream, Object data) throws IOException {
        if (data instanceof Byte) {
            dataOutputStream.writeByte((byte) data);
        } else if (data instanceof Short) {
            dataOutputStream.writeShort((short) data);
        } else if (data instanceof Character) {
            dataOutputStream.writeChar((char) data);
        } else if (data instanceof Integer) {
            dataOutputStream.writeInt((int) data);
        } else if (data instanceof Long) {
            dataOutputStream.writeLong((long) data);
        } else if (data instanceof Float) {
            dataOutputStream.writeFloat((float) data);
        } else if (data instanceof Double) {
            dataOutputStream.writeDouble((double) data);
        } else if (data instanceof Boolean) {
            dataOutputStream.writeBoolean((boolean) data);
        } else if (data instanceof LocalDateTime) {
            byte[] bytes = ((LocalDateTime) data).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")).getBytes(StandardCharsets.UTF_8);
            dataOutputStream.writeInt(bytes.length);
            dataOutputStream.write(bytes);
        } else if (data instanceof Date) {
            byte[] bytes = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(data).getBytes(StandardCharsets.UTF_8);
            dataOutputStream.writeInt(bytes.length);
            dataOutputStream.write(bytes);
        } else if (data instanceof String) {
            byte[] bytes = ((String) data).getBytes(StandardCharsets.UTF_8);
            dataOutputStream.writeInt(bytes.length);
            dataOutputStream.write(bytes);
        } else if (data instanceof byte[]) {
            dataOutputStream.writeInt(((byte[]) data).length);
            dataOutputStream.write((byte[]) data);
        } else {
            // 转成json字符串，转成字节数组
            String json = JSON.toJSONString(data);
            byte[] cache = json.getBytes(StandardCharsets.UTF_8);
            dataOutputStream.writeInt(cache.length);
            dataOutputStream.write(cache);
        }
    }
}
